<script>
import Album from './album.vue'
import axios from 'axios'
export default {
  components: {
    Album
  },
  props: {
    maxSize: {
      type: Number,
      default: 10
    },
    rowSize: {
      type: Number,
      default: 5
    },
    folder: {
      type: String,
      default: 'pictures'
    },
    headers: {
      type: Object,
      default() {
        return {}
      }
    },
    urls: {
      type: Array,
      default() {
        return []
      }
    },
    pictures: {
      type: Array,
      default() {
        return []
      }
    }

  },
  data() {
    return {
      allowUpload: true,
      url: `${process.env.VUE_APP_UPLOAD}api/v1/upload/file`
    }
  },
  computed: {
    urlsSync: {
      get() {
        return this.urls
      },
      set(urls) {
        this.$emit('update:urls', urls)
      }
    },
    picturesSync: {
      get() {
        return this.pictures
      },
      set(pictures) {
        this.$emit('update:pictures', pictures)
      }
    }
  },
  mounted() {

  },
  methods: {
    upload(file, onChange) {
      const data = new FormData()
      data.append('file', file)
      data.append('folder', this.folder)

      return axios
        .post(this.url, data, {
          headers: { ...this.headers },
          onUploadProgress(e) {
            const { loaded, total } = e
            const progress = parseFloat((loaded / total * 100).toFixed(2))
                        onChange?.(progress)
          }
        })
        .then(result => result.data)
    },
    batchUpload(tasks) {
      return Promise.allSettled(
        tasks.map(task => {
          const {
            file,
            handlers: { onStart, onChange, onSuccess, onFailed }
          } = task

          onStart()

          return this.upload(file, onChange)
            .then(result => onSuccess(result.data.path))
            .catch(onFailed)
        })
      )
    },
    clear() {
      this.$refs.album?.clear?.()
    }
  }
}
</script>

<template>
  <Album
    ref="album"
    :max-size="maxSize"
    :upload="batchUpload"
    :allow-upload="allowUpload"
    :row-size="rowSize"
    :picture-list.sync="picturesSync"
    :urls="urlsSync"
  />
</template>
